<template>
	<view style="padding-bottom: 20rpx;">
		<!-- <view style="margin-left: 223rpx;margin-top: 20rpx;">
			<uploader />
		</view> -->
		<view class="install-container">

			<!-- 用户信息 -->
			<!-- 如果需要使用 validateFunction 自定义校验规则,则不能采用 uni-forms 的 rules 属性来配置校验规则，
			这时候需要通过ref，在onReady生命周期调用组件的setRules方法绑定验证规则 -->
			<uni-forms :value="params" ref="form" validateTrigger="bind" class="word5">
				<uni-forms-item required label="所属项目：" name="项目名称">
					<view :class="label3 == '请选择所属项目' ? 'color':''" class="tap" @click="handleTap('picker3')">{{label3}}
					</view>
					<lb-picker v-model="params['项目名称']" ref="picker3" @click="handleTap('picker3')" @input="binddata('项目名称',$event)"
						mode="selector" :list="projectList" :dataset="{ name: 'label3' }" @confirm="handleConfirm"
						@cancel="handleCancel">
					</lb-picker>
				</uni-forms-item>
				<uni-forms-item label="角色分组：">
					<view :class="label5 == '请选择角色分组' ? 'color':''" class="tap" @click="handleTap('picker5')">{{label5}}
					</view>
					<lb-picker ref="picker5" @click="handleTap('picker5')"
						mode="selector" :list="groupList" :dataset="{ name: 'label5' }" @confirm="handleConfirm"
						@cancel="handleCancel">
					</lb-picker>
				</uni-forms-item>
				<uni-forms-item required label="角色类型：" name="角色名称">
					<view :class="label4 == '请选择角色类型' ? 'color':''" class="tap" @click="handleTap('picker4')">{{label4}}
					</view>
					<lb-picker ref="picker4" @click="handleTap('picker4')" @input="binddata('角色名称',$event)"
						mode="selector" :list="roleList" :dataset="{ name: 'label4' }" @confirm="handleConfirm"
						@cancel="handleCancel">
					</lb-picker>
				</uni-forms-item>
				<uni-forms-item required label="任务名称：" name="任务名称">
					<input style="font-size: 30rpx;" maxlength="18" v-model="params['任务名称']" placeholder="请输入任务名称"
						@input="binddata('任务名称',$event.detail.value)">
				</uni-forms-item>
				<uni-forms-item required label="任务描述：" name="任务描述">
					<input style="font-size: 30rpx;" maxlength="18" v-model="params['任务描述']" placeholder="请输入任务描述"
						@input="binddata('任务描述',$event.detail.value)">
				</uni-forms-item>
				<uni-forms-item required label="任务优先级：" name="任务优先级">
					<view :class="label == '请选择任务优先级' ? 'color':''" class="tap" @click="handleTap('picker')">{{label}}
					</view>
					<lb-picker ref="picker" @click="handleTap('picker')" @input="binddata('任务优先级',$event)"
						mode="selector" :list="taskLevelList" :dataset="{ name: 'label' }" @confirm="handleConfirm"
						@cancel="handleCancel">
					</lb-picker>
				</uni-forms-item>
				<uni-forms-item required label="任务执行人：">
					<view v-if="!params['执行人'].length" :class="label1 == '请选择任务执行人' ? 'color':''" class="tap"
						@click="toChoose(query,3)">{{label1}}</view>
					<!-- <view @click="toChoose(query,1)" v-for="(item,index) in query" style="margin: 2px;display: inline-block;" :key="index">
						<text >{{item.name}};</text>
					</view> -->
					<view @click="toChoose(query,3)" v-for="(item,index) in params['执行人']"
						style="margin: 2px;display: inline-block;" :key="index">
						<text>{{item}};</text>
					</view>
					<!-- <lb-picker ref="picker1" @click="handleTap('picker1')" mode="selector" :list="unitList" :dataset="{ name: 'label1' }"
					 @confirm="handleConfirm1" @cancel="handleCancel">
					</lb-picker> -->
				</uni-forms-item>
				<uni-forms-item required label="任务抄送人：">
					<!-- <view :class="label2 == '请选择任务抄送人' ? 'color':''" class="tap" @click="handleTap('picker2')">{{label2}}</view>
					<lb-picker ref="picker2" @click="handleTap('picker2')" mode="selector" :list="unitList" :dataset="{ name: 'label2' }"
					 @confirm="handleConfirm2" @cancel="handleCancel">
					</lb-picker> -->
					<view v-if="!params['抄送人'].length" :class="label2 == '请选择任务抄送人' ? 'color':''" class="tap"
						@click="toChoose1(query1,0)">{{label1}}</view>
					<!-- <view @click="toChoose1(query1,0)" v-for="(item,index) in query1" style="margin: 2px;display: inline-block;" :key="index">
						<text >{{item.name}};</text>
					</view> -->
					<view @click="toChoose1(query1,0)" v-for="(item,index) in params['抄送人']"
						style="margin: 2px;display: inline-block;" :key="index">
						<text>{{item}};</text>
					</view>
				</uni-forms-item>
				<uni-forms-item required label="开始时间" name="开始日期">
					<xp-picker mode="ymdhis" :action-position="actionPosition" :history="history"
						:year-range="[2020,2030]" @confirm="confirmStart">
						<!-- <button>年月日时分秒</button> -->
						<input disabled type="text" v-model="params['开始日期']" placeholder="请选择开始时间">
					</xp-picker>
				</uni-forms-item>
				<uni-forms-item required label="结束时间" name="结束日期">
					<xp-picker mode="ymdhis" :action-position="actionPosition" :history="history"
						:year-range="[2020,2030]" @confirm="confirmEnd">
						<!-- <button>年月日时分秒</button> -->
						<input disabled type="text" v-model="params['结束日期']" placeholder="请选择结束时间">
					</xp-picker>
				</uni-forms-item>
			</uni-forms>
			<view style="margin-top: 20rpx;"></view>
			<uploader @input='onChange'></uploader>
		</view>
		<view class="title">
			<view class="left">子任务列表</view>
			<view class="right">
				<text class="add" @click="addChildTask">
					+
				</text>
				<text @click="addChildTask" style="color: #5094FF;">新增子任务</text>
			</view>
		</view>
		<view v-if="params['子任务'].length" class="content">
			<child-task @add="addChildTask" @detail="editChildTask" @delete="deleteTask" :children="params['子任务']">
			</child-task>
		</view>
		<view v-if="!params['子任务'].length" class="empty">暂无子任务</view>
		<button class="btn" @click="submitForm">提交</button>
	</view>
</template>

<script>
	import uploader from '@/components/my-components/image-uploader.vue'
	import DatePicker from '@/myComponents/date-picker.vue'
	import LbPicker from '@/components/lb-picker/index.vue'
	// import pgTree from '@/components/pg-tree/pg-tree';
	import dayjs from 'dayjs'
	import ChildTask from '@/components/childTask.vue'
	// import { showModal } from '@/utils/common.js'
	var that;
	export default {
		components: {
			uploader,
			DatePicker,
			LbPicker,
			ChildTask
		},
		data() {
			return {
				groupList: [],
				roleList: [],
				taskTree: {},
				id: null,
				query: [],
				query1: [],
				detail: {
					userIds: [],
					organizeIds: []
				},
				sendObj: [],
				uoData: [],
				isChoose: [],
				actionPosition: "bottom",
				history: true,
				isShow: false,
				type: '',
				showModal: false,
				unitList: [],
				list: [],
				label: '请选择任务优先级',
				label1: '请选择任务执行人',
				label3: '请选择所属项目',
				label4: '请选择角色类型',
				value: '',
				value1: '',
				value2: '',
				// installTypeList: this.$type.installTypeList,
				params: {
					项目id: null,
					项目名称: null,
					分组名称: null,
					角色id: null,
					角色名称: null,
					任务名称: null,
					任务描述: null,
					任务优先级: null,
					执行人id: [],
					抄送人id: [],
					执行人: [],
					抄送人: [],
					开始日期: null,
					结束日期: null,
					图片: [],
					子任务: []
				},
				params1: {
					任务id: null
				},
				taskLevelList: this.$type.taskLevelList,
				taskLevelObj: this.$type.taskLevelObj,
				//表单验证规则
				rules: {
					任务名称: {
						rules: [{
							required: true,
							errorMessage: '请填写任务名称',
						}]
					},
					任务描述: {
						rules: [{
							required: true,
							errorMessage: '请填写任务描述',
						}]
					},
					任务优先级: {
						rules: [{
							required: true,
							errorMessage: '请选择任务优先级',
						}]
					},
					// 执行人id: {
					// 	rules: [{
					// 		validateFunction: (rule, value, data, callback) => {
					// 			if (this.params.执行人id.length !== 0) {
					// 				// 通过返回 resolve
					// 				callback()
					// 			} else {
					// 				// 不通过返回 reject(new Error('错误信息'))
					// 				callback('请选择任务执行人')
					// 			}
					// 		}
					// 	}]
					// },
					// 抄送人id: {
					// 	rules: [{
					// 		validateFunction: (rule, value, data, callback) => {
					// 			if (this.params.抄送人id.length !== 0) {
					// 				// 通过返回 resolve
					// 				callback()
					// 			} else {
					// 				// 不通过返回 reject(new Error('错误信息'))
					// 				callback('请选择任务抄送人')
					// 			}
					// 		}
					// 	}]
					// },
					开始日期: {
						rules: [{
							required: true,
							errorMessage: '请填写开始日期',
						}]
					},
					结束日期: {
						rules: [{
							required: true,
							errorMessage: '请填写结束日期'
						}]
					}
				}
			}
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
			// this.params1.任务id = +options.id
			// if(options.id) {
			// 	this.getTaskDetail()
			// }
			this.getRoleGroup()
			this.getRoleList()
			console.log('出发load')
			if(options.item) {
				this.params = JSON.parse(options.item)
				this.params.tempId = this.params.任务id || new Date().getTime()
				uni.setStorageSync('taskTree', this.params)
			}
			if (options.taskId) {
				this.taskTree = uni.getStorageSync('taskTree')
				this.params.tempId = options.taskId
				let params = this.findTask(this.taskTree)
				Object.assign(this.params, params)
			} else { //新增
				this.params.tempId = this.params.id || new Date().getTime()
				this.taskTree = uni.getStorageSync('taskTree') || this.params
				if (options.parentId) {
					this.params.parentId = options.parentId
				} else {
					this.params = this.taskTree
				}
			}
			this.label = this.params.任务优先级 && this.taskLevelObj[this.params.任务优先级]
			this.label3 = this.params.项目名称
			this.label4 = this.params.角色名称
			// this.getTaskDetail()
		},
		onShow() {
			// this.params.抄送人 = uni.getStorageSync('query1').map(item => item.name)
			// this.params = uni.getStorageSync('taskTree') || this.params
			this.taskTree = uni.getStorageSync('taskTree') || this.params
			let that = this
			this.params = this.findTask(this.taskTree) || this.params
			if (uni.getStorageSync('query')) {
				this.params.执行人 = uni.getStorageSync('query').map(item => item.name)
			}
			if (uni.getStorageSync('query1')) {
				this.params.抄送人 = uni.getStorageSync('query1').map(item => item.name)
			}
			this.label = this.taskLevelObj[this.params.任务优先级]
			if (this.params.parentId) {
				let that = this
			
				function findParent(item) {
					let result = null
					if (item.tempId == that.params.parentId) {
						result = item
					} else {
						if (item.子任务 && item.子任务.length > 0) {
							for (let i = 0; i < item.子任务.length; i++) {
								let t = findParent(item.子任务[i])
								if (t) {
									result = t;
									break;
								}
							}
						}
					}
					return result
				}
			
				let parent = findParent(this.taskTree)
				console.log('parent', parent)
				if (parent) {
					let params = this.findTask(this.taskTree)
					//如果树里没有这个任务，才添加到父节点的子任务里
					if (!params && !this.params.id) {
						if (parent.子任务) {
							parent.子任务.push(this.params)
						} else {
							parent.子任务 = [this.params]
						}
					}
				}
				uni.setStorageSync('taskTree', this.taskTree)
			}
			console.log('onshow findTask', this.params)
		},
		mounted() {
			that = this
		},
		watch: {
			query(newVal, oldVal) {
				if (newVal !== oldVal) {
					console.log('变化了')
					this.binddata('执行人id', [this.query[0].id])
					// this.params.抄送人id = this.query[0].id
					this.params.执行人 = JSON.parse(JSON.stringify(this.query))
					// uni.setStorageSync('query', this.query)
				}
			},
			query1(newVal, oldVal) {
				if (newVal !== oldVal) {
					this.binddata('抄送人id', this.query1.map(item => item.id))
					// this.params.抄送人 = JSON.parse(JSON.stringify(this.query1))
					// uni.setStorageSync('query1', this.query1)
				}
			}
		},
		methods: {
			onChange(e) {
				this.params.图片 = e
			},
			getRoleGroup() {
				this.$http.post('worksys/roleGroup/list', this.params1).then(res => {
					console.log('分组:', res)
					if(res.code === 10000) {
						res.data.list = res.data.list || []
						res.data.list.forEach(item => {
							item.label = item.分组名称
							item.value = item.分组名称
						})
						res.data.list.push({
							分组id: 0,
							分组名称: '组外角色',
							label: '组外角色',
							value: '组外角色'
						})
						this.groupList = res.data.list
					}
				})
			},
			getRoleList() {
				this.$http.post('worksys/role/list', this.params2).then(res => {
					console.log('角色:', res)
					res.data.list = res.data.list || []
					res.data.list.forEach(item => {
						item.label = item.角色名称
						item.value = item.角色名称
					})
					this.roleList = res.data.list
				})
			},
			getTaskDetail() {
				this.$http.post('taskSystem/task/info', this.params1).then(res => {
					if(res.code === 10000) {
						console.log(res)
						res.data.开始日期 = dayjs(res.data.开始日期).format('YYYY-MM-DD HH:mm:ss')
						res.data.结束日期 = dayjs(res.data.结束日期).format('YYYY-MM-DD HH:mm:ss')
						this.params = res.data
						this.label = this.$type.taskLevelObj[res.data.任务优先级]
						uni.setStorageSync('taskTree', this.params)
						this.taskTree = this.params
					}
				})
			},
			toChoose(item, type) {
				uni.setStorageSync('taskTree', this.taskTree)
				let items = this.isChoose.length > 0 ? JSON.stringify(this.isChoose) : JSON.stringify(this.query)
				uni.navigateTo({
					url: `../choosePerson/choosePerson?item=${items}&type=${type}`
				})
			},
			toChoose1(item, type) {
				uni.setStorageSync('taskTree', this.taskTree)
				let items = this.isChoose.length > 0 ? JSON.stringify(this.isChoose) : JSON.stringify(this.query1)
				uni.navigateTo({
					url: `../chooseUser/chooseUser?item=${items}&type=${type}`
				})
			},
			binddata(name, value) {
				// 通过 input 事件设置表单指定 name 的值
				this.$refs.form.setValue(name, value)
			},
			confirmStart(e) {
				console.log(e)
				this.params.开始日期 = e.value
				this.binddata('开始日期', e.value)
			},
			confirmEnd(e) {
				console.log(e)
				this.params.结束日期 = e.value
				this.binddata('结束日期', e.value)
			},
			findTask(tree) {
				let that = this

				function findTask(item) {
					let result = null
					if (item.tempId == that.params.tempId) {
						result = item
					} else {
						if (item.子任务 && item.子任务.length > 0) {
							for (let i = 0; i < item.子任务.length; i++) {
								let t = findTask(item.子任务[i])
								if (t) {
									result = t;
									break;
								}
							}
						}
					}
					return result
				}
				return findTask(tree)
			},
			addChildTask() {
				if (uni.getStorageSync('query')) {
					this.params.执行人id = [uni.getStorageSync('query')[0].id]
					this.params.执行人 = [uni.getStorageSync('query')[0].name]
				}
				if (uni.getStorageSync('query1')) {
					this.params.抄送人id = uni.getStorageSync('query1').map(item => item.id)
					this.params.抄送人 = uni.getStorageSync('query1').map(item => item.name)
				}
				let params = this.findTask(this.taskTree)
				console.log('params:', params)
				// Object.assign(params, this.params)
				
				// uni.setStorageSync('taskTree', this.taskTree)
				
				uni.removeStorageSync('query')
				uni.removeStorageSync('query1')
				uni.navigateTo({
					url: '/taskSystem/createTask/createTask?parentId=' + this.params.tempId
				})
			},
			editChildTask(index) {
				let params = this.params.子任务[index]
				params.parentId = this.params.任务id
				uni.setStorageSync('taskTree', this.params)
				uni.navigateTo({
					url: `/taskSystem/createTask/createTask?parentId=${params.tempId}&taskId=${params.tempId}`
				})
				// uni.navigateTo({
				// 	url: `/taskSystem/editTask/editTask?item=${JSON.stringify(params)}`
				// })
				
			},
			deleteTask(index) {
				uni.showModal({
					title: '提示',
					content: '确认删除该子任务吗',
					success: (res) => {
						if (res.confirm) {
							this.params.子任务.splice(index, 1)
							uni.setStorageSync('taskTree', this.params)
						} else if (res.cancel) {
							uni.showToast({
								title: '取消删除',
								icon: 'none'
							})
						}
					}
				});
			},
			submitTask() {
				//提交的时候把任务详情修改，并保存到树里
				if (this.params.parentId) {
					let params = this.findTask(this.taskTree)
					Object.assign(params, this.params)
					uni.setStorageSync('taskTree', this.taskTree)
					
					uni.navigateBack({
						delta: -1
					})
				} else {
					//没有父节点就是第一层，自己就是树
					this.taskTree = this.params
					uni.setStorageSync('taskTree', this.taskTree)
					console.log(this.params)
				}
			},
			handleTap(name) {
				this.$refs[name].show()
			},
			// 任务优先级
			handleConfirm(e) {
				console.log(e)
				if (e) {
					const name = e.dataset.name
					const label = e.item.label
					this.params.任务优先级 = e.item.id
					console.log(this.params)
					// this.params4.education = e.item.id
					if (name && label) {
						this[name] = label
					}
				}
			},
			submitForm(form) {

				// console.log('this.resident', this.resident)
				// 手动提交表单
				this.$refs.form.submit().then(res => {
					if (uni.getStorageSync('query')) {
						this.params.执行人id = [uni.getStorageSync('query')[0].id]
						this.params.执行人 = [uni.getStorageSync('query')[0].name]
					}
					if (uni.getStorageSync('query1')) {
						this.params.抄送人id = uni.getStorageSync('query1').map(item => item.id)
						this.params.抄送人 = uni.getStorageSync('query1').map(item => item.name)
					}
					// console.log(this.params)
					// return
					if (!this.params.执行人id.length) {
						uni.showToast({
							title: '请选择任务执行人',
							icon: 'none'
						})
						return
					}
					if (!this.params.抄送人id.length) {
						uni.showToast({
							title: '请选择任务抄送人',
							icon: 'none'
						})
						return
					}
					res.开始日期 = res.开始日期 && dayjs(res.开始日期).format('YYYY-MM-DDTHH:mm:ssZ')
					res.结束日期 = res.结束日期 && dayjs(res.结束日期).format('YYYY-MM-DDTHH:mm:ssZ')
					console.log('表单数据信息：', res);
					//提交的时候把任务详情修改，并保存到树里
					if (this.params.parentId) {
						console.log('触发')
						let params = this.findTask(this.taskTree)
						// params.开始日期 = params.开始日期 && dayjs(params.开始日期).format('YYYY-MM-DDTHH:mm:ssZ')
						// params.结束日期 = params.结束日期 && dayjs(params.结束日期).format('YYYY-MM-DDTHH:mm:ssZ')
						Object.assign(params, this.params)
						uni.setStorageSync('taskTree', this.taskTree)
						uni.removeStorageSync('query')
						uni.removeStorageSync('query1')
						uni.navigateBack({
							delta: -1
						})
						uni.showToast({
							title: '添加成功'
						})
					} else {
						//没有父节点就是第一层，自己就是树
						console.log(this.params)
						this.taskTree = this.params
						let params = JSON.parse(JSON.stringify(this.params))
						params.开始日期 = params.开始日期 && dayjs(params.开始日期).format('YYYY-MM-DDTHH:mm:ssZ')
						params.结束日期 = params.结束日期 && dayjs(params.结束日期).format('YYYY-MM-DDTHH:mm:ssZ')
						uni.setStorageSync('taskTree', this.taskTree)
						// this.addTask(Object.assign({}, this.params, res))
						this.editTask(params)
					}
					// console.log(this.params)
					// this.addTask(obj)
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						icon: 'none',
						title: "表单字段填写错误，请检查"
					})
				})
			},
			editTask(params) {
				uni.showLoading({
					mask: true
				})
				this.$http.post('taskSystem/task/addUpdate', params).then(res => {
					console.log(res)
					if (res.code === 10000) {
						uni.showToast({
							title: '新建成功'
						})
						// uni.removeStorageSync('taskTree')
						uni.removeStorageSync('query')
						uni.removeStorageSync('query1')
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.title {
		padding: 0 14rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 40rpx;
		font-size: 34rpx;
		position: relative;

		.left {
			font-size: 32rpx;
			// &:before {
			// 	content: '';
			// 	position: absolute;
			// 	top: 12rpx;
			// 	left: 24rpx;
			// 	width: 6rpx;
			// 	height: 34rpx;
			// 	background-color: #5094FF;
			// }
		}

		.right {
			// display: flex;
		}

		.add {
			font-size: 32rpx;
			font-weight: bold;
			color: #5094FF;
			margin-right: 10rpx;
		}
	}

	.empty {
		// width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 174rpx;
		color: #999;
	}

	.install-container {
		padding-bottom: 90rpx;
	}

	.color {
		color: #808080;
	}

	.btn {
		margin-top: 60rpx;
		width: 568rpx;
		height: 80rpx;
		// position: fixed;
		bottom: 0;
		line-height: 80rpx;
		margin-left: 80rpx;
		// margin-top: 160rpx;
		background: linear-gradient(to right, #3350D9, #1152FC);
		// background-color: #1152FC;
		color: #fff;
	}

	// .add-btn {
	// 	position: fixed;
	// 	bottom: 40rpx;
	// 	left: 0;
	// 	right: 0;
	// 	color: #fff;
	// 	background-color: #1152FC;
	// }
</style>
